<template>
  <div class="container">
    <el-card>
      <img class="logo" src="../../assets/logoicon.png" alt="极客园">
      <!-- 表单 -->
      <el-form :model="loginForm" ref="loginForm" :rules="loginRules" status-icon>
        <el-form-item prop="mobile">
          <el-input placeholder="请输入手机号" v-model="loginForm.mobile"></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input placeholder="请输入验证码" v-model="loginForm.code"></el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox :value="true">我已阅读并同意「用户协议」和「隐私条款」</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login()">登 录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
// 导入token工具
import auth from '@/utils/auth'
export default {
  name: 'LoginIndex',
  data () {
    // 自定义手机号码格式规则
    const checkMobile = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback()
      } else {
        callback(new Error('手机号格式不对'))
      }
    }
    return {
      loginForm: {
        mobile: '13200000000',
        code: '246810'
      },
      loginRules: {
        mobile: [
          { required: true, trigger: 'blur', message: '请输入手机号' }, {
            validator: checkMobile, trigger: 'blur'
          }
        ],
        code: [
          { required: true, trigger: 'blur', message: '请输入验证码' }, {
            len: 6, trigger: 'blur', message: '验证码是6个字符'
          }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.loginForm.validate(async valid => {
        if (valid) {
          try {
            // 请求
            const res = await this.$http.post('/v1_0/authorizations', this.loginForm)
            // 成功，保存token本地
            localStorage.setItem('geek-client-pc-store', res.data.data.token)
            auth.setToken(res.data.data.token)
            // 跳转首页
            this.$router.push('/')
          } catch (error) {
            // 失败
            this.$message.error(error.response.data.message || '登陆失败')
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
  .container{
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    right: 0;
    background: url(../../assets/background.png) no-repeat center / contain;
    background-size: cover;
    .el-card{
      width: 440px;
      height: 380px;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%,-50%);
      box-shadow:0 0 50px rgba(0,0,0,0.1);
      .logo{
        width: 200px;
        display: block;
        margin: 0 auto 20px;
      }
    }
    .el-form{
      padding: 0 20px;
      .el-button{
        width: 100%;
      }
    }
  }
</style>
